import './style/index.css';
import React from "react";
import { Input,Checkbox, Button, Tooltip, message } from 'antd';
import { WeaNewScroll ,WeaTools} from 'ecCom';
import trim from 'lodash/trim';
import isEqual from 'lodash/isEqual';
import {WeaLocaleProvider} from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
import { ReplyAddStore } from '../../stores/reply/add';

export interface MainProps {
	editorId ?: string ;
	appendHtmlToCKEditor:Function;
	visible: boolean;
	showComponent: Function;
	params:any;
	replyAdd:ReplyAddStore;
	windowTop?:any
}
/**
 * @功能
 */
export default class Main extends React.Component <MainProps,any>{
	constructor(props) {
		super(props);
		this.state = {
			time:"",
			inputId:`wfat-input-text-${new Date().getTime()}`
		}
	}

	getAtInfo(){
		const {replyAdd,params = {}} = this.props;
		return replyAdd.getAtInfo(params);
	}

	setAtInfo=(k,v)=>{
		const {replyAdd,params = {}} = this.props;
		replyAdd.setAtInfo(k,v,params);
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.visible) {
			const atInfo  = this.getAtInfo();
			const {data={}} = atInfo;
			const { atitems=[] } = data;
			this.setAtInfo("data",{...data, selectUser: [], _atitems: atitems.slice(0, 100) });
		}
	}

	shouldComponentUpdate(nextProps, nextState) {
		const atInfo  = this.getAtInfo();
		const {data={}} = atInfo;
		const {q ='',selectUser=[],_atitems=[],atitems=[]} = data;
		if(!nextState){
			nextState = {};
		}
		return !isEqual(atitems, nextState.atitems) ||
			!isEqual(_atitems, nextState._atitems) ||
			!isEqual(selectUser, nextState.selectUser) ||
			q !== nextState.q ||
			this.props.visible !== nextState.visible;
	}

	getAtListCom=()=>{
		const {replyAdd,params = {}} = this.props;
		let key = "cube_at_"+params.modeId+"_"+params.billid;
		let data:any = replyAdd.atInfo[key+"_data"];
		const {time} = this.state;
		
		if (data&&data._atitems&&data._atitems.length > 0) {
			const { _atitems = []} = data;
			return <WeaNewScroll height={125}>
				<ul key={time}>
					{
						_atitems.map(item => {
							return <li>
								<Checkbox onClick={this.selectedAtUser.bind(this, item)}>
									<span onClick={this.addOneAtToCkeditor.bind(this, item)} style={{ cursor: 'pointer' }}>{item.data}</span>
								</Checkbox>
							</li>
						})
					}
				</ul>
			</WeaNewScroll>
		} else {
			return <div className='wfat-no-data'>
				<span className={`wfat-no-data-icon icon-coms-blank`} />
				<span className="wfat-no-data-tip">{getLabel(83553, '暂无数据')}</span>
			</div>
		}
	}

	render() {
		const atInfo = this.getAtInfo();
		const {data={}} = atInfo;
		const { q='' } = data;
		const { visible } = this.props;
		// const {time} = this.state;
		return (
			<div className="cube-ckeditor-wfat">
				<div className="wea-cb-item" onClick={() => { this.props.showComponent(visible ? '' : 'CubeAt') }}>
					<Tooltip placement="topLeft" title={getLabel(386973,"在回复评论框中输入@可直接选择具有本条数据查看权限的人")}>
						<span className={`wea-cbi-icon icon-coms-at`} />
					</Tooltip>
				</div>
				<div className="wfat-content" style={{ display: visible ? 'block' : 'none' }}>
					<div className="triangle_border_nw"></div>
					<div className="wfat-input">
						<Input type="text"  value={q}  onChange={this.doSearch.bind(this)} id={this.state.inputId}  onClick={this.addFocus}/>
						<span className={`wfat-input-search icon-coms-search`} />
					</div>
					<div className="wfat-list" >
						{this.getAtListCom()}
						
					</div>
					<div className="wfat-footer">
						<Button size="small" onClick={this.addAtToCKEditor.bind(this)} className="ant-btn-1">{getLabel(382958, "确定")}</Button>
						<Button size="small" onClick={this.doCancel.bind(this)} className="ant-btn-2">{getLabel(201,"取消")}</Button>
					</div>
				</div>
			</div>
		)
	}

	addFocus=()=>{
		let dom = document.getElementById(this.state.inputId);
		if(dom){
			dom.focus()
		}
	}

	selectedAtUser(user) {
		const {data={}} = this.getAtInfo();
		const { selectUser = [] } = data;
		let _selectUser = selectUser.filter(o => o.uid !== user.uid);
		if (_selectUser.length === selectUser.length) {
			_selectUser.push(user);
		}
		this.setAtInfo("data",{...data,selectUser:_selectUser});
	}

	refreshTime=()=>{
		this.setState({time:new Date().getTime()});
	}

	addAtToCKEditor(_) {
		const {data={}} = this.getAtInfo();
		const { selectUser = [] } = data;

		if (selectUser.length === 0) {
			message.warning(getLabel(383750,'请至少选择一个!'), 5);
		} else {
			let atHtmlArr:any = [];
			selectUser.map(o => {
				atHtmlArr.push(`<a href="/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/${o.uid}" atsome="@${o.uid}" contenteditable='false' style="cursor:pointer;text-decoration:none !important;margin-right:8px;color:#2777c1!important" target="_blank">@${o.data}&nbsp;</a>`);
			});
			this.props.appendHtmlToCKEditor && this.props.appendHtmlToCKEditor(this.appendStyle(atHtmlArr.join('')));
			this.setAtInfo('data',{...data,selectUser:[],q:''});
			this.refreshTime();
			this.props.showComponent('');
		}
	}

	addOneAtToCkeditor(user, e) {
		this.props.appendHtmlToCKEditor && this.props.appendHtmlToCKEditor(this.appendStyle(`<a href="/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/${user.uid}" atsome="@${user.uid}" contenteditable="false" style="cursor:pointer;text-decoration:none !important;margin-right:8px;color:#2777c1!important" target="_blank">@${user.data}</a>`));
		const atInfo  = this.getAtInfo();
		const {data={}} = atInfo;
		this.setAtInfo('data',{...data,selectUser:[],q:''});
		this.props.showComponent('');
		e.stopPropagation();
	}

	appendStyle(info) {
		const { editorId = "",windowTop} = this.props;
		let _wrapped_contents = info;
		const windowNew = windowTop ? windowTop: WeaTools.WindowFunc.getTop();
		if( windowNew.CK_REF[editorId]){
			const instances = windowNew.CK_REF[editorId].getEditor().ui.instances;
			if (instances) {
				const font = instances.Font['_'].value || 'Microsoft YaHei';
				const fontsize = instances.FontSize['_'].value || 12;
				_wrapped_contents = `<span style="font-family:'${font}';font-size:${fontsize}px" >${info}&nbsp;&#8203;</span>`;
			}
		}
		return _wrapped_contents;
	}

	doCancel() {
		const atInfo  = this.getAtInfo();
		const {data={}} = atInfo;
		this.setAtInfo("data",{ ...data,q: '', selectUser: [] });
		this.refreshTime();
		this.props.showComponent('');
	}

	arrayContains(selectUser, user) {
		return selectUser.filter(o => o.uid === user.uid).length > 0;
	}

	doSearch(e) {
		const atInfo  = this.getAtInfo();
		const {data={}} = atInfo;
		const {  atitems=[] } = data;
		let q = e.target.value;
		let r = [];
		if (trim(q).length === 0) {
			r = r.concat(atitems);
		} else {
			r = atitems.filter(o => {
				return o.data.indexOf(q) >= 0 || (trim(o.datapy).length > 0 && o.datapy.indexOf(q.toUpperCase()) >= 0);
			});
		}
		this.setAtInfo("data",{...data, _atitems: r.slice(0, 100), q: q});
		this.refreshTime();
	}
}
